package com.helasasa.maxfunds.lineofcredit.cashloan.ghana.screen.repay

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.graphics.Typeface
import android.net.Uri
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.helasasa.maxfunds.lineofcredit.cashloan.ProjectApplication
import com.helasasa.maxfunds.lineofcredit.cashloan.R
import com.helasasa.maxfunds.lineofcredit.cashloan.databinding.ActivityGhanaRepayBinding
import com.helasasa.maxfunds.lineofcredit.cashloan.ghana.http.hitPoint
import com.helasasa.maxfunds.lineofcredit.cashloan.ghana.screen.subview.HotlineGhanaDialog
import org.json.JSONObject

class RepayGhanaActivity : AppCompatActivity() {

    private lateinit var repayViewModel: RepayGhanaViewModel
    private lateinit var binding: ActivityGhanaRepayBinding
    private lateinit var adapter: RepayGhanaPageAdapter

    @SuppressLint("NotifyDataSetChanged")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        // 数据模型
        repayViewModel = ViewModelProvider(this)[RepayGhanaViewModel::class.java]

        // 关联布局
        binding = ActivityGhanaRepayBinding.inflate(layoutInflater)
        setContentView(binding.root)

        // 用到的控件
        val back = binding.navbarLeft
        val hotline = binding.navbarRight
        val loading = binding.loading
        val dueDate = binding.dueDate
        val dueAmount = binding.dueAmount
        val list = binding.list
        val submit = binding.submit

        // 初始化adapter
        adapter = RepayGhanaPageAdapter(emptyList())
        list.layoutManager = LinearLayoutManager(this)
        list.adapter = adapter

        // 查询页面详情
        val orderId = intent.getStringExtra("orderId") ?: ""
        repayViewModel.orderId = orderId
        if (orderId.isBlank()) {
            finish()
            return
        }

        // 页面loading状态接口监听
        repayViewModel.loadingResult.observe(this@RepayGhanaActivity, Observer {
            val loadingResult = it ?: return@Observer

            if (loadingResult) {
                loading.visibility = View.VISIBLE
            } else {
                loading.visibility = View.GONE
            }
        })

        // 页面详情接口监听
        repayViewModel.pageDetailResult.observe(this@RepayGhanaActivity, Observer {
            val pageDetailResult = it ?: return@Observer

            loading.visibility = View.GONE
            if (pageDetailResult.error != null) {
                // TODO: 失败
                showMessage(pageDetailResult.error)
            }
            if (pageDetailResult.success != null) {
                // TODO: 成功
                dueDate.text = pageDetailResult.success.optString("repayDate")
                dueAmount.text = pageDetailResult.success.optString("totalRepay")
            }
            if (pageDetailResult.list != null) {
                // TODO: 成功
                adapter.dataList = pageDetailResult.list
                adapter.notifyDataSetChanged()
            }
        })

        // 还款链接接口监听
        repayViewModel.repayUrlResult.observe(this@RepayGhanaActivity, Observer {
            val repayUrlResult = it ?: return@Observer

            loading.visibility = View.GONE
            if (repayUrlResult.error != null) {
                // TODO: 失败
                showMessage(repayUrlResult.error)
            }
            if (repayUrlResult.success != null) {
                // TODO: 成功
                val intent = Intent(Intent.ACTION_VIEW, Uri.parse(repayUrlResult.success)).apply {
                    flags = Intent.FLAG_ACTIVITY_NEW_TASK
                }
                if (intent.resolveActivity(ProjectApplication.instance.packageManager) != null) {
                    startActivity(intent)
                } else {
                    startActivity(Intent.createChooser(intent, "Please select a browser to open"))
                }
            }
        })

        // 流程接口监听
        repayViewModel.mainProcessResult.observe(this@RepayGhanaActivity, Observer {
            val mainProcessResult = it ?: return@Observer

            loading.visibility = View.GONE
            if (mainProcessResult.error != null) {
                showMessage(mainProcessResult.error)
            }

            if (mainProcessResult.success != null) {
                repayViewModel.nextRouter(mainProcessResult.success)
            }
        })

        // 页面需要跳转监听
        repayViewModel.nextRouterResult.observe(this@RepayGhanaActivity, Observer {
            val nextRouterResult = it ?: return@Observer

            loading.visibility = View.GONE
            startNextActivity(nextRouterResult.nextPage)
        })

        // 点击申请
        back.setOnClickListener {
            finish()
        }

        // 点击客服
        hotline.setOnClickListener {
            // 客服弹框
            HotlineGhanaDialog().showNow(supportFragmentManager, "hotline")
            hitPoint("SHOW_HOTLINE")
        }

        // 点击还款
        submit.setOnClickListener {
            loading.visibility = View.VISIBLE
            repayViewModel.repayUrl()
            hitPoint("REPAY_COMMIT")
        }

        // 更新页面详情
        loading.visibility = View.VISIBLE
        repayViewModel.pageDetail()
    }

    override fun onResume() {
        super.onResume()
        hitPoint(type = this::class.java.simpleName, isPageStart = true)
        if (repayViewModel.isFirstLoad) {
            repayViewModel.isFirstLoad = false
        } else {
            // 查询状态
            repayViewModel.mainProcess()
        }
    }

    override fun onPause() {
        super.onPause()
        hitPoint(type = this::class.java.simpleName, isPageEnd = true)
    }
}


class RepayGhanaPageAdapter(
    var dataList: List<JSONObject>
) :
    RecyclerView.Adapter<RepayGhanaPageAdapter.ViewHolder>() {

    override fun onCreateViewHolder(
        parent: ViewGroup,
        viewType: Int,
    ): ViewHolder {
        val view = LayoutInflater.from(parent.context)
            .inflate(R.layout.view_ghana_repay_activity_adapter, parent, false)
        return ViewHolder(view)
    }

    inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        private val title: TextView = view.findViewById(R.id.title)
        private val detail: TextView = view.findViewById(R.id.detail)

        fun bindData(item: JSONObject) {
            title.text = item.optString("showName")
            detail.text = item.optString("showDetail")

            val isBold = item.optString("title")
            if (isBold.contains("YES", true)) {
                title.setTextColor(Color.parseColor("#222222"))
                title.typeface = Typeface.defaultFromStyle(Typeface.BOLD)
                detail.typeface = Typeface.defaultFromStyle(Typeface.BOLD)
            } else {
                title.setTextColor(Color.parseColor("#999999"))
                title.typeface = Typeface.defaultFromStyle(Typeface.NORMAL)
                detail.typeface = Typeface.defaultFromStyle(Typeface.NORMAL)
            }
        }
    }

    @SuppressLint("SetTextI18n")
    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val data: JSONObject = dataList[position]
        holder.bindData(data)
    }

    override fun getItemCount(): Int {
        return dataList.size
    }
}

fun Context.showMessage(message: String) {
    Toast.makeText(applicationContext, message, Toast.LENGTH_SHORT).show()
}

fun Context.startNextActivity(
    activity: Class<out AppCompatActivity>? = null,
    params: HashMap<String, String> = HashMap()
) {
    val nextActivity = activity ?: return
    try {
        val intent = Intent(this, nextActivity)
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_NEW_TASK)
        params.keys.forEach { gKey ->
            intent.putExtra(gKey, params[gKey])
        }
        startActivity(intent)
    } catch (e: Exception) {
        e.printStackTrace()
    }
}
